package kr.ac.konkuk.db.quadtree.server.service;

import java.util.List;
import java.util.Set;

import kr.ac.konkuk.db.quadtree.QuadTree;
import kr.ac.konkuk.db.quadtree.callback.SearchOperator;
import kr.ac.konkuk.db.quadtree.impl.ByteWKTQuadTree;
import kr.ac.konkuk.db.quadtree.server.service.QuadTreeService.Iface;
import kr.ac.konkuk.db.quadtree.util.JTSUtils;

import org.apache.thrift.TException;

import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;

public class QuadTreeServiceHandler implements Iface {
	private QuadTree<List<Byte>> qt = null;
	
	public QuadTreeServiceHandler(QuadTree<Geometry> qt) {
		this.qt = new ByteWKTQuadTree(qt);
	}

	public Set<String> insert(List<Byte> rowKey, List<Byte> geom)
			throws TException {
		return this.qt.insert(rowKey, geom);
	}

	public boolean remove(List<Byte> rowKey) throws TException {
		return this.qt.remove(rowKey);
	}

	@Override
	public Set<String> search(double x1, double y1, double x2, double y2,
			final Operating op) throws TException {
		return qt.search(new Envelope(x1, x2, y1, y2), new SearchOperator() {
			@Override
			public boolean operate(Geometry g1, Envelope env) {
				Geometry g2 = JTSUtils.toGeometry(env);
				switch(op) {
				case INTERSECT:
					return g1.intersects(g2);
				case CONTAINS:
					return g1.contains(g2);
				case COVERS:
					return g1.covers(g2);
				case DISJOINT:
					return g1.disjoint(g2);
				}
				
				return false;
			}
		});
	}

	@Override
	public Set<String> searchByGeometry(List<Byte> searchGeom, Operating op) throws TException {
		// TODO Auto-generated method stub
		return null;
	}


}
